<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\ApiResult;
use App\Models\User;
use App\Services\Base\CacheService;
use App\Services\Base\MsgService;
use App\Traits\FileTools;
use App\Traits\RedisTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ApiBaseController extends Controller
{

    use FileTools, RedisTool;

    public function success($data = null, $message = "操作成功")
    {
        return $this->responseJson(ApiResult::success($data, $message));
    }

    public function failure($code = 500, $message = "操作失败", $data = null)
    {
        return $this->responseJson(ApiResult::failure($code, $message, $data));
    }

    protected function responseJson($data)
    {
        return response()->json($data);
    }


    public function getUid(Request $request)
    {
        $token = $request->bearerToken();
        $user = CacheService::hGet(R_LOGIN_TOKEN_INFO, $token);
        if ($user) {
            $user = json_decode($user, true);
            return $user['uid'];
        } else {
            return "";
        }
    }

    public function getDefaultLang(Request $request)
    {
        return MsgService::getLang($request);
    }


    private $m_header;

    public function getHeader($name)
    {
        if (isset($this->m_header[$name])) {
            if (is_array($this->m_header[$name])) {
                return $this->m_header[$name][0];
            } else {
                return $this->m_header[$name];
            }
        }
        return "";
    }

    public function getHeaders(Request $request)
    {
        $this->m_header = $request->header();
        $info['ip'] = $this->getIp() ?? "127.0.0.1"; // $a=$c??$b; 等同于 $a=isset($c)?$c:$b;
        $params = [
            'brand' => 'brand',
            'version' => 'version',
            'model' => 'model',
            'device_id' => 'device-id',
            'source' => 'source',
        ];

        foreach ($params as $k => $v) {
            $info[$k] = $this->getHeader($v);
        }
        $info['device_id'] = $info['device_id'] ?: User::DEFAULT_DEVICE_ID;
        $info['location'] = "";

        // 预定义参数
        $info = array_merge([
            "register_type" => User::DEFAULT_REGISTER_TYPE,
            "area_id" => User::DEFAULT_AREA_ID,
        ], $info);
        try {
            if ($info['ip'] != "127.0.0.1") {
                $location = CacheService::hGet(R_IP, $info['ip'], true);
                if (!$location) {
                    $location = geoip()->getLocation($info['ip'])->toArray();
                    CacheService::hSet(R_IP, $info['ip'], $location, true);
                }

                $info['location'] = $location['city'] . " " . $location['iso_code'];
                $info['iso_code'] = $location['iso_code'];
            }
        } catch (\Exception $e) {

        }
        return $info;
    }


    public function getIp()
    {
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip); // just to be safe
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        return request()->ip(); // it will return server ip when no client ip found
    }

    public function verifyField($input, $rules)
    {
        $errors = Validator::make($input, $rules)->errors();
        if (!blank($errors->first())) return response()->json(['code' => 500, 'msg' => $errors->first()]);
    }
}
